%=============================================================================
%   This program computes the minimum likelihood procedure for the exact local
%   Whittle estimation of d
%
%   (The only variable here is d, since concentrated)
%
%   Daniela Osterrieder and Peter Schotman
%   The Volatility of Long-term Bond Returns:
%   Persistent Interest Shocks and Time-varying Risk Premiums
%
%   REVIEW OF ECONOMICS AND STATISTICS
%==============================================================================

function R_d = ELW_ShiPhi06(d,m,lambda,x,n)

theta_d=ones(n,1);
for k=2:n
    theta_d(k,1)=theta_d(k-1,1)*((k-2-d)/(k-1));
end;
clear k

% Filter the original series x, in order to get the series (1-l)^d *x
if (d==0)
    filtered_x=x;
elseif (d==1)
    filtered_x=[0; x(2:end,1)-x(1:end-1,1)];
else
    filtered_x=zeros(n,1);
    for t=1:n
        filtered_x(t,1)=ones(1,t)*(theta_d(1:t,1).*x(t:-1:1,1));
    end;
    clear t
end;
   
%Now define the discrete Fouries transform of the series x (evaluated at
%each frequencies lambda)
w_ELW_pre=(n/sqrt(2*pi*n))*exp((2/n)*1i*pi*[0:1:n-1]').*(ifft(filtered_x));
%change order (as in Shimotsu and Phillips, 2006)
help=w_ELW_pre(1,1);
w_ELW=[w_ELW_pre(2:end,1); help];
clear help

%Use the dft's to construct the periodogram of x at each frequency lambda
I_ELW=w_ELW(1:m,1).*(conj(w_ELW(1:m,1))); %has length m

%Calculate \hat{G}
Ghat=(1/m)*(ones(1,m)*I_ELW);

%Now define the objective function, which depends on d
R_d=log(Ghat)-2*d*(1/m)*(ones(1,m)*log(lambda(1:m,1)));


